import 'package:shared_preferences/shared_preferences.dart';

class Storage {
  static late SharedPreferences prefs; // 本地存储

  // 初始化
  static void initialization() async {
    prefs = await SharedPreferences.getInstance();
  }

  // 设置字符串(带有效时长-秒)
  static Future<bool> setString(String key, String value, int? expires) async {
    bool? status = await prefs.setString(key, value);
    if (expires != null) {
      int timeStamp = DateTime.now().millisecondsSinceEpoch + expires * 1000;
      bool? status2 = await prefs.setInt('$key:expires', timeStamp);
      return status == true && status2 == true;
    }
    return status == true;
  }

  // 获取字符串(带有效时长-秒)
  static String? getString(String key) {
    int? expires = prefs.getInt('$key:expires');
    if (expires != null) {
      int timeStamp = DateTime.now().millisecondsSinceEpoch;
      if (timeStamp > expires) return null;
    }
    return prefs.getString(key);
  }

  // 移除字符串(带有效时长-秒)
  static void remove(String key) {
    prefs.remove('$key:expires');
    prefs.remove(key);
  }
}

// 获取token
String? getToken() {
  return Storage.getString('token');
}

// 设置token
Future<bool> setToken(String value, int? expires) async {
  bool result = await Storage.setString('token', value, expires);
  return result;
}

// 移除token
void removeToken() {
  Storage.remove('token');
}
